package org.chw.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: EchoClientHandler
 * @Description: 回声客户端Handler
 * @Autor: Vincent.Chen
 * @Create: 2018/6/8 16:07
 * @Version: 1.0
 **/
@ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private static final Logger LOGGER = LoggerFactory.getLogger(EchoClientHandler.class);

    /**
     * @return void
     * @Author: Vincent.Chen
     * @Description: 数据后从服务器接收到调用
     * @Date 2018/6/8 16:17
     * @Param [channelHandlerContext, byteBuf]
     **/
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) {
        LOGGER.info("Client Received:{}", byteBuf.toString(CharsetUtil.UTF_8));
    }

    /**
     * @return void
     * @Author: Vincent.Chen
     * @Description: 服务器的连接被建立后调用
     * @Date 2018/6/8 16:17
     * @Param [ctx]
     **/
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty,hello!", CharsetUtil.UTF_8));
    }

    /**
     * @return void
     * @Author: Vincent.Chen
     * @Description: 捕获一个异常时调用
     * @Date 2018/6/8 16:17
     * @Param [ctx, cause]
     **/
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        LOGGER.error("ERROR:", cause);
        ctx.close();
    }
}
